# -*- coding: utf-8 -*-
"""
导出设置界面
"""
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
                            QLabel, QPushButton, QComboBox, QLineEdit, QGroupBox,
                            QFileDialog, QMessageBox, QTextEdit, QProgressBar,
                            QCheckBox, QSpinBox)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont
from core.export_manager import ExportManager
from config import DEFAULT_EXPORT_PATH, SUPPORTED_FORMATS, DEFAULT_FORMAT
from utils.user_settings import user_settings
import os
from datetime import datetime

class ExportWidget(QWidget):
    """导出设置界面"""
    
    export_started = pyqtSignal(str, str, str, bool)  # format, path, filename, overwrite
    export_cancelled = pyqtSignal()
    
    def __init__(self, export_manager: ExportManager):
        super().__init__()
        self.export_manager = export_manager
        self.dict_data = {}
        
        self.init_ui()
        self.setup_connections()
        self.load_user_settings()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        
        # 导出设置组
        settings_group = QGroupBox("导出设置")
        settings_layout = QGridLayout(settings_group)
        
        # 导出格式
        settings_layout.addWidget(QLabel("导出格式:"), 0, 0)
        self.format_combo = QComboBox()
        for format_name, extension in SUPPORTED_FORMATS.items():
            self.format_combo.addItem(f"{format_name} ({extension})", format_name)
        # 默认值将在load_user_settings中设置
        settings_layout.addWidget(self.format_combo, 0, 1)
        
        # 文件保存路径
        settings_layout.addWidget(QLabel("保存路径:"), 1, 0)
        path_layout = QHBoxLayout()
        self.path_edit = QLineEdit()
        # 默认值将在load_user_settings中设置
        self.path_edit.setPlaceholderText("请选择文件保存路径")
        path_layout.addWidget(self.path_edit)
        
        self.browse_button = QPushButton("浏览")
        self.browse_button.clicked.connect(self.browse_path)
        path_layout.addWidget(self.browse_button)
        settings_layout.addLayout(path_layout, 1, 1)
        
        # 文件名
        settings_layout.addWidget(QLabel("文件名:"), 2, 0)
        self.filename_edit = QLineEdit()
        self.filename_edit.setPlaceholderText("请输入文件名（不含扩展名）")
        settings_layout.addWidget(self.filename_edit, 2, 1)
        
        # 自动生成文件名
        self.auto_filename_checkbox = QCheckBox("自动生成文件名")
        # 默认值将在load_user_settings中设置
        self.auto_filename_checkbox.toggled.connect(self.on_auto_filename_toggled)
        settings_layout.addWidget(self.auto_filename_checkbox, 3, 1)
        
        layout.addWidget(settings_group)
        
        
        # 导出预览组
        preview_group = QGroupBox("导出预览")
        preview_layout = QVBoxLayout(preview_group)
        
        # 预览信息
        self.preview_text = QTextEdit()
        self.preview_text.setMaximumHeight(150)
        self.preview_text.setReadOnly(True)
        preview_layout.addWidget(self.preview_text)
        
        layout.addWidget(preview_group)
        
        # 导出按钮
        button_layout = QHBoxLayout()
        
        self.export_button = QPushButton("开始导出")
        self.export_button.clicked.connect(self.start_export)
        self.export_button.setStyleSheet("QPushButton { background-color: #4CAF50; color: white; font-weight: bold; padding: 10px; }")
        button_layout.addWidget(self.export_button)
        
        self.cancel_button = QPushButton("取消导出")
        self.cancel_button.clicked.connect(self.cancel_export)
        self.cancel_button.setEnabled(False)
        self.cancel_button.setStyleSheet("QPushButton { background-color: #f44336; color: white; font-weight: bold; padding: 10px; }")
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        layout.addWidget(self.progress_bar)
        
        layout.addStretch()
    
    def setup_connections(self):
        """设置信号连接"""
        # 格式变化时更新预览
        self.format_combo.currentTextChanged.connect(self.update_preview)
        
        # 路径变化时更新预览
        self.path_edit.textChanged.connect(self.update_preview)
        
        # 文件名变化时更新预览
        self.filename_edit.textChanged.connect(self.update_preview)
        
        # 自动生成文件名变化时更新预览
        self.auto_filename_checkbox.toggled.connect(self.update_preview)
        
        # 添加设置变化时的保存
        self.path_edit.textChanged.connect(self.save_user_settings)
        self.format_combo.currentTextChanged.connect(self.save_user_settings)
        self.auto_filename_checkbox.toggled.connect(self.save_user_settings)
    
    def set_dict_data(self, dict_data: dict):
        """设置字典数据"""
        self.dict_data = dict_data
        # 调试信息（生产环境可注释掉）
        # print(f"导出界面设置字典数据: 数据是否为空={not bool(dict_data)}, 表数量={dict_data.get('total_tables', 0) if dict_data else 0}")
        self.update_preview()
        
        # 自动生成文件名
        if self.auto_filename_checkbox.isChecked() and dict_data:
            db_name = dict_data.get('database_info', {}).get('database_name', '')
            default_filename = self.export_manager.generate_default_filename(db_name)
            self.filename_edit.setText(default_filename)
    
    def browse_path(self):
        """浏览保存路径"""
        path = QFileDialog.getExistingDirectory(
            self, "选择保存路径", self.path_edit.text()
        )
        if path:
            self.path_edit.setText(path)
    
    def on_auto_filename_toggled(self, checked: bool):
        """自动生成文件名选项变化"""
        if checked and self.dict_data:
            db_name = self.dict_data.get('database_info', {}).get('database_name', '')
            default_filename = self.export_manager.generate_default_filename(db_name)
            self.filename_edit.setText(default_filename)
        
        self.filename_edit.setEnabled(not checked)
    
    def update_preview(self):
        """更新导出预览"""
        if not self.dict_data:
            self.preview_text.setText("请先连接数据库并选择要导出的表")
            return
        
        # 获取导出格式
        format_name = self.format_combo.currentData()
        format_extension = SUPPORTED_FORMATS[format_name]
        
        # 获取文件名
        filename = self.filename_edit.text().strip()
        if not filename:
            filename = "未命名"
        
        # 获取完整文件路径
        file_path = os.path.join(self.path_edit.text(), f"{filename}{format_extension}")
        
        # 生成预览信息
        db_info = self.dict_data.get('database_info', {})
        preview_info = f"""导出预览:
数据库: {db_info.get('database_name', '未知')}
导出格式: {format_name} ({format_extension})
保存路径: {file_path}
表数量: {self.dict_data.get('total_tables', 0)}
字段总数: {sum(len(table.get('columns', [])) for table in self.dict_data.get('tables', []))}
索引总数: {sum(len(table.get('indexes', [])) for table in self.dict_data.get('tables', []))}

导出选项:
• 表结构信息: 是
• 索引信息: 是
• 字段注释: 是"""
        
        self.preview_text.setText(preview_info)
    
    def start_export(self):
        """开始导出"""
        if not self.validate_inputs():
            return
        
        # 获取导出参数
        format_name = self.format_combo.currentData()
        file_path = self.path_edit.text().strip()
        filename = self.filename_edit.text().strip()
        
        # 检查文件是否已存在
        format_extension = SUPPORTED_FORMATS[format_name]
        full_file_path = os.path.join(file_path, f"{filename}{format_extension}")
        
        overwrite = False
        if os.path.exists(full_file_path):
            reply = QMessageBox.question(
                self, "文件已存在", 
                f"文件 '{full_file_path}' 已存在，是否覆盖？",
                QMessageBox.Yes | QMessageBox.No
            )
            if reply != QMessageBox.Yes:
                return
            overwrite = True
        
        # 更新界面状态
        self.set_export_enabled(False)
        self.progress_bar.setVisible(True)
        self.progress_bar.setValue(0)
        
        # 发送导出开始信号
        self.export_started.emit(format_name, file_path, filename, overwrite)
    
    def cancel_export(self):
        """取消导出"""
        reply = QMessageBox.question(
            self, "确认取消", 
            "确定要取消导出吗？",
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            self.export_cancelled.emit()
            self.set_export_enabled(True)
            self.progress_bar.setVisible(False)
    
    def set_export_enabled(self, enabled: bool):
        """设置导出按钮状态"""
        self.export_button.setEnabled(enabled)
        self.cancel_button.setEnabled(not enabled)
        
        # 禁用/启用设置控件
        widgets = [self.format_combo, self.path_edit, self.browse_button, 
                  self.filename_edit, self.auto_filename_checkbox]
        for widget in widgets:
            widget.setEnabled(enabled)
    
    def validate_inputs(self) -> bool:
        """验证输入"""
        if not self.dict_data:
            QMessageBox.warning(self, "导出失败", "请先连接数据库并选择要导出的表")
            return False
        
        if not self.path_edit.text().strip():
            QMessageBox.warning(self, "导出失败", "请选择文件保存路径")
            self.path_edit.setFocus()
            return False
        
        if not self.filename_edit.text().strip():
            QMessageBox.warning(self, "导出失败", "请输入文件名")
            self.filename_edit.setFocus()
            return False
        
        # 验证文件名
        filename = self.filename_edit.text().strip()
        invalid_chars = '<>:"/\\|?*'
        if any(char in filename for char in invalid_chars):
            QMessageBox.warning(self, "导出失败", f"文件名包含非法字符: {invalid_chars}")
            self.filename_edit.setFocus()
            return False
        
        return True
    
    def update_progress(self, progress: int, message: str = ""):
        """更新进度"""
        self.progress_bar.setValue(progress)
        if message:
            self.preview_text.append(f"[{progress}%] {message}")
    
    def export_finished(self, success: bool, result: str):
        """导出完成"""
        self.set_export_enabled(True)
        self.progress_bar.setVisible(False)
        
        if success:
            self.preview_text.append(f"导出成功: {result}")
        else:
            self.preview_text.append(f"导出失败: {result}")
    
    def load_user_settings(self):
        """加载用户设置"""
        try:
            # 加载导出路径
            export_path = user_settings.get_export_path()
            self.path_edit.setText(export_path)
            
            # 加载导出格式
            export_format = user_settings.get_export_format()
            format_text = f"{export_format} ({SUPPORTED_FORMATS[export_format]})"
            self.format_combo.setCurrentText(format_text)
            
            # 加载自动生成文件名设置
            auto_filename = user_settings.get_auto_filename()
            self.auto_filename_checkbox.setChecked(auto_filename)
            
            
        except Exception as e:
            print(f"加载用户设置失败: {e}")
    
    def save_user_settings(self):
        """保存用户设置"""
        try:
            # 保存导出路径
            user_settings.set_export_path(self.path_edit.text().strip())
            
            # 保存导出格式
            export_format = self.format_combo.currentData()
            if export_format:
                user_settings.set_export_format(export_format)
            
            # 保存自动生成文件名设置
            user_settings.set_auto_filename(self.auto_filename_checkbox.isChecked())
            
            
        except Exception as e:
            print(f"保存用户设置失败: {e}")
